/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package masterclient;

import Protocol.ClientObject;
import Protocol.ComProtocol;
import Protocol.ReturnObject;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

    /**
    * Deze klasse zorgt ervoor dat het maken en laden van backups mogelijk wordt..
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
public class BackupManagement extends JPanel {
    private File file;
    private String path;
    private Writer writer = null;
    private ComProtocol cp;
    private String result = "";
    private ReturnObject ro;
    private ArrayList<String> stringList;
    
    public BackupManagement(){
        setLayout(null);
        stringList = new ArrayList();
    }
    
    /**
    * Verstuurd een ComProtocol met het verzoek een lijst bestanden in de backups map terug te sturen.
    * @author Roman Wiedijk
    * @since 03-06-2012
    */
    
    public JComboBox refreshElements(JComboBox cbox){
        cbox.removeAllItems();
        ClientObject o = null;
        cp = new ComProtocol("localhost", 5555);
        o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getUpdateBackupList(), "");
        cp.send(o);
        stringList = (ArrayList) cp.recieve();
        
        for(int i=0;i<stringList.size();i++){
            cbox.addItem(stringList.get(i));
            //System.out.println(stringList.get(i));
        }
        
        cp.close(); 
        
        return cbox;
    }
    
    /**
    * Verstuurd twee Auth select queries om de juiste gegevens uit de database te halen.
    * Hierna worden deze gegevens verwerkt en wordt een verzoek verzonden deze gegevens op te slaan.
    * @author Roman Wiedijk
    * @since 03-06-2012
    */
    
    public int createBackup(){
        int success = 0;
        String tableName = "";
        String total = "";
        String query = "";
        ClientObject o = null;
        
        for(int i=0;i<2;i++){
            cp = new ComProtocol("localhost", 5555);
        
            if(i==0){
                o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getAuthSelectQuery(), "SELECT [Name], [Password], [isMaster] FROM [User] WHERE Name != \'System\'");
                tableName = "User";
            }
            if(i==1){
                o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getAuthSelectQuery(), "SELECT [Query], [Description], [isActive] FROM [Query]");
                tableName = "Query";
            }
            
            cp.send(o);
            ro = (ReturnObject) cp.recieve(); 
            cp.close(); 
            
            if(ro != null){
                if(ro.getMessage().equals("ok")){ 
                    total += verwerkReturnObject(ro, tableName) + "\r\n";
                }
            } else {
                System.out.println("Geen RO terug");
            }
        }
        
        cp = new ComProtocol("localhost", 5555);
        o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getBackupCreateQuery(), total);
        cp.send(o);
        ro = (ReturnObject) cp.recieve(); 
        cp.close(); 
        
        if(ro != null){
            if(ro.getMessage().equals("ok")){ 
                System.out.println("Backup maken gelukt."); 
                success = 1;
            }
        } else {
            System.out.println("Aanmaken mislukt.");
        }
        return success;
    }
    
    /**
    * Als de query correct is worden de ArrayLists verwerkt in de vorm van een insert query.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public String verwerkReturnObject(ReturnObject ro, String tableName){
        int columnCounter = 0;
        int rowCounter = 0;
        /*
        if(tableName.equals("User")){
            result = "INSERT INTO [Auth].[dbo].[User]([Name], [Password], [isMaster]) VALUES";
        } else if (tableName.equals("Query")){
            result = "INSERT INTO [Auth].[dbo].[Query]([Query], [Description], [isActive]) VALUES";
        }
        */
        result = "INSERT INTO [Auth].[dbo].["+ tableName + "](";
        
        for(String s :ro.getKolommen()){
            
            result += "[" + s.toString() + "]";
            if(columnCounter < ro.getKolommen().size()-1){
                result += ", ";
            }
            if(columnCounter == ro.getKolommen().size()-1){
                result += ") VALUES";
            }
            columnCounter++;
        }
        for(ArrayList a:ro.getRijen()){
            //System.out.println(ro.getRijen().size());
            int valueCounter = 1;
            for(Object s : a){
                //System.out.println("Row: " + rowCounter + " | Value: " + valueCounter + " | Column: " + columnCounter);
                
                if(valueCounter == 1){
                    result += "(\'";
                }
                
                result += s.toString();
                
                if(valueCounter != columnCounter){
                    result += "\',\'";
                }
                if(valueCounter == columnCounter && rowCounter != ro.getRijen().size()-1){
                    result += "\'),";
                }
                if(valueCounter == columnCounter && rowCounter == ro.getRijen().size()-1){
                    result += "\');";
                }
                if(valueCounter == columnCounter){
                    rowCounter++;
                }
                valueCounter++;
            }
        }
        System.out.println(result);
        return result;
    }
    
    /**
    * Deze functie voert de aangemaakte inser query uit.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public void executeQuery(String executableQuery){
        cp = new ComProtocol("localhost", 5555);
        ClientObject o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getUpdateQuery(), executableQuery);
        cp.send(o);
        ReturnObject ro = (ReturnObject) cp.recieve(); 
        cp.close();        
        if(ro != null){
            if(ro.getMessage().equals("ok")){                
                System.out.println("Query uitgevoerd.");
            }
        }else{
            System.out.println("Geen RO terug");
        }  
    }
    
   
    /**
    * Leest een bestand in en voert deze uit met behulp van de executeQuery() functie.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public int loadBackup(String file){
        int success = 0;
        cp = new ComProtocol("localhost", 5555);
        ClientObject o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getBackupLoadQuery(), file);
        cp.send(o);
        ReturnObject ro = (ReturnObject) cp.recieve(); 
        cp.close();        
        if(ro != null){
            if(ro.getMessage().equals("ok")){                
                System.out.println("Query uitgevoerd.");
                success = 1;
            }
        }else{
            System.out.println("Geen RO terug");
        }  
        return success;
    }
    
    /**
    * Verstuurd een deleteBackup verzoek naar de server met het geselecteerde bestand.
    * @author Roman Wiedijk
    * @since 01-06-2012
    */
    
    public int deleteBackup(String file){
        int success = 0;
        cp = new ComProtocol("localhost", 5555);
        ClientObject o = new ClientObject("system", "54b53072540eeeb8f8e9343e71f28176", cp.getDeleteBackup(), file);
        System.out.println(file);
        cp.send(o);
        ReturnObject ro = (ReturnObject) cp.recieve(); 
        cp.close(); 
        
        if(ro != null){
            if(ro.getMessage().equals("ok")){                
                success = 1;
            }
        }else{
            System.out.println("Geen RO terug");
        }
        return success;
    }
}
